package com.woniu.controller;

import com.woniu.constant.Constant;
import com.woniu.entity.Result;
import com.woniu.utils.BaseController;
import com.woniu.utils.QiNiuUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Api(tags = "文件上传")
public class UploadController extends BaseController {
    @Autowired
   private StringRedisTemplate stringRedisTemplate;
    @ApiOperation("文件上传")
    @PostMapping("/img")
    public Result upload(@RequestPart MultipartFile file) throws IOException {
        // 1. 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 2. 重新设置文件的名称
        String uuid = UUID.randomUUID().toString();
        // 文件的名称 = uuid + 源文件的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid.replaceAll("-", "") + substring;
        // 3. 调用图片上传的工具类
        QiNiuUploadUtils.uploadFile(file.getBytes(), fileName);
//        AliyunUploadUtils.uploadOneFile(file,fileName);
       stringRedisTemplate.opsForSet().add(Constant.REDIS_ALL_UPLOAD_IMAGE,fileName);
        // 4. 响应数据
        return toDataResult(fileName);
    }
    @ApiOperation("删除图片")
    @GetMapping("/delete")
    public Result delete(String fileName){
        QiNiuUploadUtils.deleteFile(fileName);
//        AliyunUploadUtils.deleteFile(fileName);
        return success();
    }
}
